# !/usr/bin/env python
# -*- coding:utf-8 -*-

import os
import json
import time
from PyQt6.QtCore import pyqtSignal
from PyQt6.QtWidgets import QDialog
from page.lr import Ui_lr_add
from service.tishi_Svc import Tishi     # 提示逻辑
from service.public_Svc import *


# ==============================================================================
# page 5.lr页面
# ==============================================================================


class Lr_add(QDialog, Ui_lr_add):
    """lr信息页面"""
    confirmed_signal_lr = pyqtSignal()

    def __init__(self, name=None):
        super().__init__()
        self.setupUi(self)  # 直接调用self的setupUi方法
        self.name = name
        self.ts = Tishi()  # 提示框

    def edit(self):
        """反显编辑页面信息"""
        self.biaoti.setText(self.name)
        self.biaoti.setReadOnly(True)  # name 不可编辑
        self.biaoti.setStyleSheet("""
            QLineEdit[readOnly="true"] {
                color: gray;               /* 文本颜色设为灰色 */
                background-color: #f0f0f0; /* 背景颜色设为浅灰色 */
                border: 1px solid gray;     边框颜色设为灰色 */
            }""")

        with open(LR_JSON, 'r', encoding='utf-8') as f:
            data = json.load(f)
            value = data.get(self.name, {})  # 获取name的数据
            lisener = value.get('lisener', (0, 0, 0, 0))

        for i in range(1, 5):
            file_path = value.get(f'tu{i}')  # 删除图片文件
            if file_path is not None and os.path.exists(file_path):
                imagelabel = getattr(self, f"label_{i}")  # 识别图显示
                imagelabel.setStyleSheet(f'''
                background-color: rgb(214, 214, 214);
                image:url(./{file_path});''')  # 设置图，相对路径
                spin_box = getattr(self, f"label_1{i}")  # 状态改变
                spin_box.setText("已截图")
                if i == 1:
                    self.tu.setCurrentIndex(1)  # 设置页面下拉项
                elif i == 4:
                    self.checkBox.setChecked(True)
                    self.label_4.setVisible(True)
                    self.label_14.setVisible(True)
                    self.widget_4.setVisible(True)
                    self.tu4.setVisible(True)
            else:
                if i == 4:
                    self.dongtai_lr()
                if f'tu{i}' in value:  # 如果没图片文件，则删除图片记录
                    del value[f'tu{i}']
                    with open(LR_JSON, 'w', encoding='utf-8') as f1:
                        json.dump(data, f1)

        for i, value in enumerate(lisener, start=1):
            spin_box = getattr(self, f"spinBox_{i}")  # 坐标赋值
            spin_box.setValue(int(value))

    def save_lr(self):
        """Graph，截图范围保存"""
        if len(self.biaoti.text()) == 0:
            self.ts.xinxi("请填写名称与截图范围")
            return
        data = {'lisener': (self.spinBox_1.value(),
                            self.spinBox_2.value(),
                            self.spinBox_3.value(),
                            self.spinBox_4.value())}
        try:
            if not os.path.exists(LR_JSON):
                # 文件不存在，直接写入新数据
                with open(LR_JSON, 'w', encoding='utf-8') as f:
                    json.dump({self.biaoti.text(): data}, f)
            else:
                # 文件存在，读取并合并数据
                with open(LR_JSON, 'r', encoding='utf-8') as f:
                    existing_data = json.load(f)
                if self.biaoti.text() not in existing_data:
                    existing_data[self.biaoti.text()] = {}
                existing_data[self.biaoti.text()].update(data)
                # 写回更新后的数据
                with open(LR_JSON, 'w', encoding='utf-8') as f:
                    json.dump(existing_data, f)
            self.ts.xinxi(f"保存成功")
            self.name = self.biaoti.text()
            self.edit()
            self.show()
        except Exception as e:
            self.ts.xinxi(f"保存出错：{e}")

    def dongtai_lr(self):
        """lr动态高度勾选"""
        is_checked = self.checkBox.isChecked()
        if not is_checked:  # 如果取消勾选，删除图片与记录
            self.label_4.setVisible(False)
            self.label_14.setVisible(False)  # 隐藏相关按钮
            self.label_4.setStyleSheet(f'''
            background-color: rgb(214, 214, 214);
            image:url(:/jl/dt_lr.jpg);''')
            self.widget_4.setVisible(False)
            self.tu4.setVisible(False)
            if self.biaoti.text():
                with open(LR_JSON, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    value = data.get(self.biaoti.text(), {})  # 获取name的数据
                    tu4 = value.get('tu4', {})
                    if 'tu4' in value:
                        del value['tu4']  # 删除记录
                        with open(LR_JSON, 'w', encoding='utf-8') as f1:
                            json.dump(data, f1)
                        os.remove(tu4)  # 删除图片
        else:
            self.label_4.setVisible(True)
            self.label_14.setVisible(True)
            self.widget_4.setVisible(True)
            self.tu4.setVisible(True)

    def identify_lr(self):
        """Graph识别图截取"""
        formatted_time = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())  # 当前时间，中文名称后面图片识别报错
        button = self.sender().objectName()                         # 获取点击的按钮名称
        path = f'Identify/{formatted_time}_lr{button}.png'            # 识别图保存地址
        spinboxes = {
            'tu1': [self.spinBox_10, self.spinBox_11, self.spinBox_12, self.spinBox_13],
            'tu2': [self.spinBox_14, self.spinBox_15, self.spinBox_16, self.spinBox_17],
            'tu3': [self.spinBox_18, self.spinBox_19, self.spinBox_20, self.spinBox_21],
            'tu4': [self.spinBox_5, self.spinBox_6, self.spinBox_7, self.spinBox_8]}
        region = tuple(sb.value() for sb in spinboxes.get(button))     # 识别图范围

        with open(LR_JSON, 'r', encoding='utf-8') as f:
            existing_data = json.load(f)
            if self.biaoti.text() not in existing_data:  # 保存判断
                self.ts.xinxi("保存Graph后，再截识别图")
                return

        if activate_window("HP LoadRunner Analysis"):  # Analysis启动判断
            time.sleep(1)
        else:
            self.ts.xinxi("没找到名称包含【HP LoadRunner Analysis】的窗口，请检查Analysis是否启动")
            return

        if button == 'tu2' or button == 'tu3':
            if activate_window("Open a New Graph", max_win=1):  # Analysis启动判断
                time.sleep(2)
            else:
                pg.hotkey('ctrl', 'a')

        pg.screenshot(path, region=region)  # 坐标+宽+高    # 截图

        if os.path.exists(path):
            file_path = existing_data.get(self.biaoti.text()).get(button)  # 删除旧图
            if file_path is not None and os.path.exists(file_path):
                os.remove(file_path)
            existing_data.get(self.biaoti.text()).update({f'{button}': path})  # 更新新图地址

            with open(LR_JSON, 'w', encoding='utf-8') as f:
                json.dump(existing_data, f)
            self.edit()
            # self.ts.xinxi("截图保存成功")
        else:
            # 文件不存在
            self.ts.xinxi("截图保存失败")

        activate_window("Lr-Graph信息编辑", max_win=1)

    def closeEvent(self, QCloseEvent):
        """窗口关闭"""
        self.confirmed_signal_lr.emit()  # 发射查询信号
